<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-12-04 16:07:30
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-04-17 18:59:10
 * @FilePath: /vue-element-admin/src/views/storeSetup/cineraryUrn/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="服务方案名称">
          <el-input
            v-model="listQuery.name"
            placeholder=""
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="服务方案金额">
          <el-input
            v-model="listQuery.price"
            placeholder=""
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>

        <el-form-item label="开始日期">
          <el-date-picker
            v-model="listQuery.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="listQuery.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="yyyy-MM-dd 23:59:59"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出
      </el-button>
    </div>
    
    <el-table empty-text='暂无数据' :data="tableList" style="width: 100%; margin-top: 30px" border>
      <el-table-column align="center" label="名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="价格" width="220">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="骨灰盅名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.ashUrnName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="产品" width="220">
        <template slot-scope="scope">
          <el-tag
            v-for="tag in scope.row.productList"
            :key="tag.name"
            closable
            type="info"
          >
            {{ tag.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="日期" width="220">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" width="220">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button
            size="mini"
            @click="handleBindProduct(row.id)"
          >
            绑定产品
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
          
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加服务方案的弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="temp"
        label-width="120px"
        label-position="right"
        class="demo-form-inline"
        :inline="true"
      >
        <el-form-item label="服务方案名称">
          <el-input v-model="temp.name" placeholder="请输入服务方案名称"/>
        </el-form-item>

        <!-- 新增价格输入框 -->
        <el-form-item label="价格">
          <el-input v-model="temp.price" placeholder="请输入价格" type="number"/>
        </el-form-item>

        <!-- 新增骨灰盅选择框 -->
        <el-form-item label="选择骨灰盅">
          <el-select
            v-model="temp.ashUrnId"
            placeholder="请选择骨灰盅"
          >
            <el-option
              v-for="urn in cineraryUrnDatas"
              :key="urn.id"
              :label="urn.name"
              :value="urn.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择产品" v-if="dialogStatus === 'update'">
          <el-select
            v-model="temp.productIds"
            multiple
            placeholder="请选择产品"
            @change="handleProductChange"
          >
            <el-option
              v-for="product in productDatas"
              :key="product.id"
              :label="product.name"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 绑定产品的弹窗 -->
    <el-dialog title="绑定产品" :visible.sync="bindProductDialogVisible">
      <el-form
        ref="bindProductForm"
        :model="bindProductForm"
        label-width="120px"
        label-position="right"
        class="demo-form-inline"
        :inline="true"
      >
        <el-form-item label="选择产品">
          <el-select
          v-model="bindProductForm.productIds"
            multiple
            placeholder="请选择产品"
            @change="handleProductChange"
          >
            <el-option
              v-for="product in productDatas"
              :key="product.id+3"
              :label="product.name"
              :value="product.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindProductDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="bindProduct()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getListQuery, create, update, deleteData, getCineraryUrnList } from '@/api/serviceScheme'
import { retailAshUrnList } from '@/api/retailAshUrn'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getList } from '@/api/product'
import { retailServicePlanAdd } from '@/api/retailServicePlan' // 导入添加服务方案的 API

export default {
  components: { Pagination },

  data() {
    return {
      tableList: [],
      listQuery: {
        pageNum: 1,
        pageSize: 20
      },
      checkStrictly: false,

      defaultProps: {
        children: 'children',
        label: 'name'
      },
      total: 0,
      listLoading: true,
      temp: {
        remark: '',
        price: '',
        name: '',
        planId: null,
        productList:[],
        ashUrnId: '' // 确保在 temp 中有 ashUrnId
      },
      downloadLoading: false,
      dialogFormVisible: false, // 添加服务方案的弹窗
      bindProductDialogVisible: false, // 绑定产品的弹窗
      bindProductForm: { // 新增绑定产品的表单对象
        productIds: [],
        ashUrnId: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      productDatas: [],
      cineraryUrnDatas: [] // 存储骨灰盅数据
    }
  },
  computed: {},
  created() {
    this.getListQuery()
    this.getProductDatas()
    this.getCineraryUrnList()
    this.getAshUrnList()
  },

  methods: {
    async getProductDatas() {
      getList().then((response) => {
        this.productDatas = response.data
      })
    },
    async getCineraryUrnList() {
      console.log('getCineraryUrnList', getCineraryUrnList)
      getCineraryUrnList().then((response) => {
        this.cineraryUrnDatas = response.data
      })
    },
    async getAshUrnList() {
      try {
        const response = await retailAshUrnList('');
        this.cineraryUrnDatas = response.data; // 存储骨灰盅数据
      } catch (error) {
        console.error('获取骨灰盅列表失败:', error);
      }
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
        this.temp.productIds=row.productList?.map(product => product.id); // 设置已绑定的产品 IDs
    },
    handleDelete(row, index) {
      deleteData(row.id).then((response) => {
        this.listLoading = true
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
        this.getListQuery()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.listLoading = false
            this.getListQuery()
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getListQuery()
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        remark: '',
        price: '',
        name: '',
        planId: null,
        productList:[],
        ashUrnId: '' // 重置骨灰盅 ID
      }
      this.bindProductForm = { // 重置绑定产品的表单对象
        productIds: [],
        ashUrnId: ''
      };
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getListQuery() {
      this.listLoading = true
      getListQuery(this.listQuery).then((response) => {
        this.tableList = response.data.records
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getListQuery()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['名称', '价格', '创建时间', '备注']
        const filterVal = ['name', 'price', 'createTime', 'remark']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    handleBindProduct(productId) {
      this.resetTemp()
      const currentRow = this.tableList.find(row => row.id === productId); // 根据 ID 查找当前行
      if (currentRow) {
        // this.bindProductForm.productIds = currentRow.productList.map(product => product.id); // 设置已绑定的产品 IDs
        this.temp.productIds=currentRow.productIds; // 设置已绑定的产品 IDs
        this.productDatas= this.productDatas
        this.bindProductForm.ashUrnId = currentRow.ashUrnId; // 设置已绑定的骨灰盅 ID
        this.temp.planId = currentRow.id; // 确保设置服务方案 ID
        this.bindProductDialogVisible = true; // 显示绑定产品的弹窗
      }
    },
    handleProductChange(value) {
      console.log('选择的产品 ID:', value)
      this.bindProductForm.productIds = value
    },
    bindProduct() {
      const id = this.temp.planId; // 获取服务方案 ID
      const productIds = this.bindProductForm.productIds; // 获取选择的产品 IDs
      const ashUrnId = this.bindProductForm.ashUrnId; // 获取选择的骨灰盅 ID
      let form = {
        id: id,
        productIds: productIds,
        ashUrnId: ashUrnId // 将骨灰盅 ID 添加到表单中
      };
      // 调用 API 提交数据
      retailServicePlanAdd(form).then(response => {
        this.$notify({
          title: '成功',
          message: '绑定产品成功',
          type: 'success',
          duration: 2000
        });
        this.bindProductDialogVisible = false; // 关闭弹窗
        this.getListQuery(); // 更新列表
      }).catch(error => {
        this.$notify.error({
          title: '错误',
          message: '绑定产品失败'
        });
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
